package com.example.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.Departments;
import com.example.entity.Staff;
import com.example.mapper.StaffMapper;
import com.example.service.IDepartmentsService;
import com.example.service.IStaffService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.vo.StaffVO;
import com.nanhang.common.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lmy
 * @since 2025-01-09
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IStaffService {

    @Autowired
    private IDepartmentsService departmentsService;


    @Override
    public PageResult<Staff> findByPage(Integer page, Integer pageSize) {
        // 1. 开始分页
        Page<Staff> page1 = this.page(new Page<>(page, pageSize));
        // 2. 封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }

    @Override
    public PageResult<Staff> search(Integer page, Integer pageSize, StaffVO vo) {
        // 1. 进行分页带条件查询
        // 1.1 封装查询条件
        QueryWrapper<Staff> wrapper = new QueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(vo.getSname()), "sname", vo.getSname());
        wrapper.like(StrUtil.isNotBlank(vo.getAddr()), "addr", vo.getAddr());
        wrapper.eq(StrUtil.isNotBlank(vo.getDid()), "cid", vo.getDid());
        // 1.2 开始分页查询
        Page<Staff> page1 = this.page(new Page<>(page, pageSize), wrapper);
        //1.3 处理学生所在班级名称
        page1.getRecords().forEach(st -> {
            Departments classes = departmentsService.getById(st.getDid());
            st.setDname(classes.getDname());
        });
        // 2. 封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }

    @Override
    public boolean add(Staff staff) {
        return this.save(staff);
    }

}
